<?php
require_once("lib/redbeanwrapper.php");
require_once("lib/simplepie/simplepie.php");

class Feed extends RedBeanModel
{
	/**
	 * Creates a new feed from an url
	 */
	static public function add($url)
	{
		// Check if this feed isn't present in the DB already
		$hit = self::search($url);
		if($hit)
			return $hit;

		$f = new Feed();
		$f->url = $url;
		$f->starred = false;

		//Save the feed's name
		$feed = new SimplePie($f->url);
		$f->name = $feed->get_title();
		$f->description = $feed->get_description();
		$f->encoding = $feed->get_encoding();
		$f->favicon = $feed->get_favicon();

		$f->save();

		return $f;
	}

	/**
	 * Checks this feed for news items and pulls them
	 */
	public function retreiveFeed()
	{
		$feed = new SimplePie($this->url);

		foreach($feed->get_items() as $item)
		{
			if(!Item::exists($item->get_id()))
			{
				$itembean = Item::add($item);
				$this->associate($itembean);
			}
		}
	}

	/**
	 * Returns a feed with url $url if there is one in the DB and returns 
	 * false if there isn't. 
	 */
	public static function search($url)
	{
		$result = Finder::where("feed", " url = :url", array(':url' => $url));
		if(count($result) > 0)
			return new Feed(current($result));
		else
			return false;
	}

	/**
	 * Returns an array of all Feed objects a certain user has a 
	 * subscription to.
	 */
	public function getFeedsForUser($username)
	{
		//TODO: Make user specific...
		$ids = RBDB::databaseAdapter()->getCol("
				SELECT feed.id
				FROM feed");
		return RBDB::redbean()->batch("Feed", $ids);
	}
}

?>
